extends CharacterBody2D
class_name EnemyAI

## AI设置
@export var detection_range: float = 200.0
@export var attack_range: float = 50.0
@export var move_speed: float = 150.0
@export var attack_cooldown: float = 1.5

## 巡逻设置
@export var patrol_radius: float = 100.0
@export var patrol_wait_time: float = 2.0

## 组件引用
@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var sprite: Sprite2D = $Sprite2D
@onready var attack_area: Area2D = $AttackArea

## 私有变量
var player: Node2D = null
var start_position: Vector2
var patrol_target: Vector2
var current_state: EnemyState = EnemyState.PATROL
var last_attack_time: float = 0.0
var patrol_timer: float = 0.0

## 状态枚举
enum EnemyState {
	PATROL,
	CHASE,
	ATTACK,
	RETURN
}

func _ready():
	start_position = global_position
	set_new_patrol_target()
	
	# 查找玩家
	player = get_tree().get_first_node_in_group("player")
	
	# 设置攻击区域
	if attack_area:
		attack_area.monitoring = false

func _physics_process(delta):
	update_state()
	update_behavior(delta)
	update_animation()

func update_state():
	if not player:
		return
	
	var distance_to_player = global_position.distance_to(player.global_position)
	
	match current_state:
		EnemyState.PATROL:
			if distance_to_player <= detection_range and can_see_player():
				current_state = EnemyState.CHASE
		
		EnemyState.CHASE:
			if distance_to_player <= attack_range:
				current_state = EnemyState.ATTACK
			elif distance_to_player > detection_range * 1.5:
				current_state = EnemyState.RETURN
		
		EnemyState.ATTACK:
			if distance_to_player > attack_range:
				current_state = EnemyState.CHASE
		
		EnemyState.RETURN:
			if global_position.distance_to(start_position) < 20:
				current_state = EnemyState.PATROL
			elif distance_to_player <= detection_range and can_see_player():
				current_state = EnemyState.CHASE

func update_behavior(delta):
	match current_state:
		EnemyState.PATROL:
			handle_patrol(delta)
		EnemyState.CHASE:
			handle_chase()
		EnemyState.ATTACK:
			handle_attack()
		EnemyState.RETURN:
			handle_return()

func handle_patrol(delta):
	if global_position.distance_to(patrol_target) < 20:
		patrol_timer += delta
		if patrol_timer >= patrol_wait_time:
			set_new_patrol_target()
			patrol_timer = 0.0
	else:
		move_towards(patrol_target)

func handle_chase():
	if player:
		move_towards(player.global_position)

func handle_attack():
	if Time.get_time_dict_from_system()["unix"] >= last_attack_time + attack_cooldown:
		attack()

func handle_return():
	move_towards(start_position)

func move_towards(target: Vector2):
	var direction = (target - global_position).normalized()
	velocity = direction * move_speed
	
	# 更新朝向
	if direction.x != 0:
		sprite.flip_h = direction.x < 0
	
	move_and_slide()

func attack():
	last_attack_time = Time.get_time_dict_from_system()["unix"]
	
	# 播放攻击动画
	if animation_player and animation_player.has_animation("attack"):
		animation_player.play("attack")
	
	# 激活攻击区域
	if attack_area:
		attack_area.monitoring = true
	
	# 延迟停用攻击区域
	await get_tree().create_timer(0.3).timeout
	if attack_area:
		attack_area.monitoring = false

func set_new_patrol_target():
	var random_angle = randf() * TAU
	patrol_target = start_position + Vector2(
		cos(random_angle) * patrol_radius,
		sin(random_angle) * patrol_radius
	)

func can_see_player() -> bool:
	if not player:
		return false
	
	var direction_to_player = (player.global_position - global_position).normalized()
	var distance_to_player = global_position.distance_to(player.global_position)
	
	# 射线检测是否有障碍物
	var space_state = get_world_2d().direct_space_state
	var query = PhysicsRayQueryParameters2D.create(
		global_position,
		global_position + direction_to_player * distance_to_player,
		1,  # 碰撞掩码
		[self]  # 排除自身
	)
	var result = space_state.intersect_ray(query)
	
	return result.is_empty()

func update_animation():
	if not animation_player:
		return
	
	if current_state == EnemyState.ATTACK:
		return
	
	if velocity.length() > 10:
		if animation_player.has_animation("walk"):
			animation_player.play("walk")
	else:
		if animation_player.has_animation("idle"):
			animation_player.play("idle")

## 攻击区域信号处理
func _on_attack_area_body_entered(body):
	if body.has_method("take_damage"):
		body.take_damage(10)  # 敌人攻击力

## 公共方法
func take_damage(damage: int):
	# 受伤逻辑
	print("Enemy took damage: ", damage)
	
	# 可以添加受伤动画、音效等
	if animation_player and animation_player.has_animation("hurt"):
		animation_player.play("hurt")

func get_state_name() -> String:
	return EnemyState.keys()[current_state]

## 调试绘制
func _draw():
	if not Engine.is_editor_hint():
		return
	
	# 绘制检测范围
	draw_circle(Vector2.ZERO, detection_range, Color.YELLOW)
	draw_circle(Vector2.ZERO, detection_range, Color.YELLOW, false, 2.0)
	
	# 绘制攻击范围
	draw_circle(Vector2.ZERO, attack_range, Color.RED)
	draw_circle(Vector2.ZERO, attack_range, Color.RED, false, 2.0)
	
	# 绘制巡逻范围
	draw_circle(start_position - global_position, patrol_radius, Color.BLUE, false, 2.0)
	
	# 绘制巡逻目标
	draw_circle(patrol_target - global_position, 5, Color.GREEN)




